package basic.study.wantOffer.chapter3;

import basic.study.wantOffer.chapter3.Problem18_.ListNode;

/**
 * @author Kevin
 * @date 2020/5/4 10:54
 * 链表环的入口节点
 * 参考：https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-/
 */
public class Problem23 {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while (true) {
            if (fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
